package com.example.securityproject.demos.manager;

import cn.hutool.core.text.AntPathMatcher;
import com.example.securityproject.demos.service.TUserService;
import com.example.securityproject.demos.vo.MenuVO;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 这个类的作用，主要是根据用户传来的请求地址，分析出请求需要的角色
 */
@Deprecated
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Resource
    private TUserService tUserService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        //取出所有的菜单权限
        List<MenuVO> allPermission = tUserService.queryMenus(null);
        for (MenuVO vo : allPermission) {
            if (!StringUtils.isEmpty(vo.getPath()) && antPathMatcher.match(vo.getPath(), requestUrl)) {
                List<MenuVO> list = allPermission.stream().filter(e -> !StringUtils.isEmpty(e.getPath()) && e.getPath().equals(requestUrl)).collect(Collectors.toList());
                String[] str = new String[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    str[i] = "ROLE_" + list.get(i).getRoleName();
                }
                return SecurityConfig.createList(str);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
